<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\RenterFeeRequest;
use App\Models\Area;
use App\Models\XcRenter;
use App\Models\XcRenterContract;
use App\Models\XcRenterFee;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\RenterRequest;

/***
 * 场租方控制层
 *
 * 说明：一个场地有多个站点，
 *      站点和设备一对一的关系，
 *      设备和流量卡是一对一的关系
 */
class RenterController extends Controller
{

    /**
     * 场租方列表
     * @param Request $request
     * @return \Illuminate\Contracts\View\View
     */
    public function index(Request $request)
    {
        $citycode = $provincecode = "";
        $crole_name = Auth::user()->roles()->get()->toArray()??"";
        if ($crole_name[0]['name'] == "root"){
            $citys = GetCitys();
        }else{
            $user = Auth::user();
            $citycode_arra = AreaUserInfo::where('userid', $user->id)->get()->toArray();
            $citycode = $citycode_arra[0]['citycode']??"";
            $provincecode_arra = Area::where('code', $citycode)->pluck('supcode')->toArray();
            $provincecode = $provincecode_arra[0]??"";
            $citys = GetCitys($citycode);
        }

        return View::make('admin.renter.index',compact('citys', 'citycode', 'provincecode'));
    }

    /**
     * 获得声租方列表数据，分页信息，有些统计信息待设备列表做完后才能取到
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function data(Request $request)
    {
        $data = $request->all();
        $user = Auth::user();

        $renter = XcRenter::query();

        if (!empty($data['keyword'])) {
            $renter->where(function ($query) use($data){
                $query->where('name','LIKE',"%".$data['keyword']."%");//->orWhere('steward_phone', '=', $data['keyword']);
            });
        }
        $res = $renter->with(["contract" => function($query){
            $query->where([['starttime', '<=', date("Y-m-d")], ['endtime', '>=', date("Y-m-d")]]);
        }])
            ->withCount("device")
            ->orderBy('id','desc')
            ->paginate($request->get('limit',10));
        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $res->total(),
            'data'  => $res->items(),
        ];
        return Response::json($data);
    }

    /**
     * 新建场租方视图
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\View
     */
    public function create(Request $request)
    {
        $action = $request->get("action", "");
        $citys = [];
        $crole_name = Auth::user()->roles()->get()->toArray()??"";
        $provincecode = $citycode = "";

        if ($crole_name[0]['name'] == "root"){
            $citys = GetCitys();
            $citycode = "420100";
        }else{
            $citycode = AreaUserInfo::GetUserCityCode();
            $provincecode_arra = Area::where('code', $citycode)->pluck('supcode')->toArray();
            $provincecode = $provincecode_arra[0]??"";
            $citys = GetCitys($citycode);
        }


        return View::make('admin.renter.create', compact('citys',"citycode", "provincecode"));
    }

    /**
     * 保存场租方信息数据
     *
     * @param RenterRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(RenterRequest $request)
    {
        $user = Auth::guard('web')->user();
        $data = $request->validated();
        $data['cuser_id'] = $user->id;
        //dd($data);
        if ($data['operation_type'] == 1){
            $data['operation_price1'] = $data['operation_price_A1']??0;
            $data['operation_price2'] = $data['operation_price_A2']??0;
        }else if ($data['operation_type'] == 2){
            $data['operation_price1'] = $data['operation_price_B1']??0;
            $data['operation_price2'] = $data['operation_price_B2']??0;
        }else{
            $data['operation_price1'] = 0;
            $data['operation_price2'] = 0;
        }
        unset($data['operation_price_A1'],$data['operation_price_A2'],$data['operation_price_B1'], $data['operation_price_B2']);

        //获得renter表ID
        $renter_data = $request->only(['name','province_code','city_code','city_name','region_code','region_name','linkman','telephone']);
        //$renter_data['cuser_id'] = $user->id;
        //获得 renter_contract 表的数据
        $contract_data = $request->only(['linkman','telephone','starttime','endtime','rente_type','rente_price','property_type','property_price','water_electricity_type','operation_type','contracturl',]);
        $contract_data['operation_price1'] = $data['operation_price1'];
        $contract_data['operation_price2'] = $data['operation_price2'];
        $contract_data['cuser_id'] = $user->id;

        //dd($data);
        try{
            $renter = XcRenter::create($renter_data);
            $contract_data['renter_id'] = $renter->id;
            $contract = XcRenterContract::create($contract_data);
            return Redirect::to(URL::route('admin.renter'))->with(['success'=>'创建成功']);
        }catch (\Exception $exception){
            return Redirect::back()->withErrors($exception->getMessage());
        }
    }


    /**
     * 合同编辑
     * @param Request $request
     * @return \Illuminate\Contracts\View\View
     */
    public function edit(Request $request)
    {
        $contract_id = $request->get("contract_id");
        $renter_id = $request->get("renter_id");
        $crole_name = Auth::user()->roles()->get()->toArray()??"";
        $provincecode = $citycode = "";

        if ($crole_name[0]['name'] == "root"){
            $citys = GetCitys();
            $citycode = "420100";
        }else{
            $citycode = AreaUserInfo::GetUserCityCode();
            $provincecode_arra = Area::where('code', $citycode)->pluck('supcode')->toArray();
            $provincecode = $provincecode_arra[0]??"";
            $citys = GetCitys($citycode);
        }

        if($contract_id){
            $contract = XcRenterContract::where("id", $contract_id)->get();
            $renter = XcRenter::where("id", $contract[0]->renter_id)->first();
        } else {
            $contract = [];
            $renter = XcRenter::where("id", $renter_id)->first();
        }

        return View::make('admin.renter.edit', compact("citys", "provincecode", "citycode", "renter", "contract", "contract_id", "renter_id"));
    }
//    public function edit(Request $request)
//    {
//        $id = $request->get("id");
//        $crole_name = Auth::user()->roles()->get()->toArray()??"";
//        $provincecode = $citycode = "";
//
//        if ($crole_name[0]['name'] == "root"){
//            $citys = GetCitys();
//            $citycode = "420100";
//        }else{
//            $citycode = AreaUserInfo::GetUserCityCode();
//            $provincecode_arra = Area::where('code', $citycode)->pluck('supcode')->toArray();
//            $provincecode = $provincecode_arra[0]??"";
//            $citys = GetCitys($citycode);
//        }
//
//        $renter = XcRenter::where("id", $id)->first();
//        $contract = XcRenterContract::where("renter_id", $renter->id)
//            ->where([['starttime', '<=', date("Y-m-d")], ['endtime', '>=', date("Y-m-d")]])
//            ->orderBy("id", "desc")->get();
//
//        return View::make('admin.renter.edit', compact("citys", "provincecode", "citycode", "renter","contract"));
//    }

    /**
     * 更新/续签合同
     *
     * @param RenterRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(RenterRequest $request)
    {
        $user = Auth::guard('web')->user();
        $renter_id   = $request->get("renter_id");   //续签合同
        $contract_id   = $request->get("contract_id");   //更新合同
        $data = $request->validated();
        $data['cuser_id'] = $user->id;
        //dd($data);
        if ($data['operation_type'] == 1){
            $data['operation_price1'] = $data['operation_price_A1']??0;
            $data['operation_price2'] = $data['operation_price_A2']??0;
        }else if ($data['operation_type'] == 2){
            $data['operation_price1'] = $data['operation_price_B1']??0;
            $data['operation_price2'] = $data['operation_price_B2']??0;
        }else{
            $data['operation_price1'] = 0;
            $data['operation_price2'] = 0;
        }
        unset($data['operation_price_A1'],$data['operation_price_A2'],$data['operation_price_B1'], $data['operation_price_B2']);

        //获得renter表ID
        $renter_data = $request->only(['name','province_code','city_code','city_name','region_code','region_name','linkman','telephone']);
        //$renter_data['cuser_id'] = $user->id;
        //获得 renter_contract 表的数据
        $contract_data = $request->only(['linkman','telephone','starttime','endtime','rente_type','rente_price','property_type','property_price','water_electricity_type','operation_type','contracturl',]);
        $contract_data['operation_price1'] = $data['operation_price1'];
        $contract_data['operation_price2'] = $data['operation_price2'];
        $contract_data['rente_price'] = $data['rente_price'] ?: 0;
        $contract_data['property_price'] = $data['property_price'] ?: 0;
        $contract_data['cuser_id'] = $user->id;

        try{
            if($renter_id){
                $contract = XcRenterContract::select('endtime')->where('renter_id', $renter_id)->where('endtime', '>=', DB::raw('"'.$contract_data['starttime'].'"'))
                    ->orderBy('id','desc')->first();
                if($contract) throw new \Exception('合同时间重叠，开始时间必须晚于：' . $contract->endtime);
                $contract_data['renter_id'] = $renter_id;
                XcRenterContract::create($contract_data);
                $msg = '续签成功';
            } else {
                $contract = XcRenterContract::select('renter_id')->where('id', $contract_id)->first();
                XcRenterContract::where('id', $contract_id)->update($contract_data);
//                XcRenter::where("id", $contract->renter_id)->update($renter_data);
                $renter_id = $contract->renter_id;
                $msg = '更新成功';
            }

            return Redirect::to(URL::route('admin.renter.contract',['renter_id' => $renter_id]))->with(['success'=>$msg]);
        }catch (\Exception $exception){
            return Redirect::back()->withErrors($exception->getMessage());
        }
    }

    /**
     * 删除场租方信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(Request $request)
    {
        $ids = $request->get('ids');
        if (!is_array($ids) || empty($ids)){
            return Response::json(['code'=>1,'msg'=>'请选择删除项']);
        }
        try{
            //目前采用逻辑删除
            //XcRenter::whereIn('id', $ids)->update(['status' => -1]);
            return Response::json(['code'=>0,'msg'=>'删除成功']);
        }catch (\Exception $exception){
            return Response::json(['code'=>1,'msg'=>'删除失败','data'=>$exception->getMessage()]);
        }
    }

    /**
     * -----------------------------------------------------水电费-------------------------------------------------------
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function weHtml(Request $request)
    {
        $id = $request->get("id");
        $contract_id = $request->get("contract_id");
        if($id){ //编辑
            $renter = XcRenterFee::where("id", $id)->first();
            $res = XcRenter::where("id", $renter->renter_id)->first();
            $renter->name = $res->name;
            $month = substr($renter->ym, -2);
            $renter->month = $month;
            $renter->months = [$month];
            $renter->year = (int)$renter->ym;
        } else { //从合同列表页面新增
            $contract = XcRenterContract::where("id", $contract_id)->first();
            //合同某一年的有效月份
            $yMonths = (new XcRenterContract())->yMonths($contract);

            $res = XcRenter::where("id", $contract->renter_id)->first();
            $renter = (object)[];
            $renter->name = $res->name;
            $renter->month = 0;
            $renter->year = (int)$yMonths['year'];
            $renter->contract_id = $contract_id;

            //有效月份里面 过滤掉已经添加的月份
            $has_months = $fees = [];
            if($yMonths['months']){
                $fees = XcRenterFee::where('contract_id', $contract->id)
                    ->where('ym', '>=', $renter->year . '-' . $yMonths['months'][0])
                    ->where('ym', '<=', $renter->year . '-' . $yMonths['months'][count($yMonths['months']) - 1])
                    ->get()->toArray();
                foreach ($fees as $val) {
                    if($val['images_url']){  //这个是必填项，拿他判断有没有填报
                        $has_months[] = substr($val['ym'], -2);
                    }
                }
            }
            $renter->months = array_diff($yMonths['months'], $has_months);
            //有效月份里面 随便拿场租与物业费 用于展示
            $renter->renter_fee = $fees ? $fees[0]['renter_fee'] : 0;
            $renter->property_fee = $fees ? $fees[0]['property_fee'] : 0;
        }

        return View::make('admin.renter.weHtml', compact("renter"));
    }

    public function months(Request $request)
    {
        $year = $request->get("year");
        $contract_id = $request->get("contract_id");
        $contract = XcRenterContract::where("id", $contract_id)->first();
        //合同某一年的有效月份
        $yMonths = (new XcRenterContract())->yMonths($contract, $year);
        //有效月份里面 过滤掉已经添加的月份
        $has_months = [];
        if($yMonths['months']){
            $fees = XcRenterFee::where('contract_id', $contract->id)
                ->where('ym', '>=', $year . '-' . $yMonths['months'][0])
                ->where('ym', '<=', $year . '-' . $yMonths['months'][count($yMonths['months']) - 1])
                ->get()->toArray();
            foreach ($fees as $val) {
                if($val['images_url']){  //这个是必填项，拿他判断有没有填报
                    $has_months[] = substr($val['ym'], -2);
                }
            }
        }
        $data = [
            'code' => 0,
            'msg'  => 'success',
            'data' => array_diff($yMonths['months'], $has_months)
        ];
        return Response::json($data);
    }

    public function weStore(RenterFeeRequest $request)
    {
        $id = $request->get("id");
        $contract_id = $request->get("contract_id");
        $data = $request->validated();
        $data['water_fee'] = $data['water_fee'] ?: 0;
        $data['electric_fee'] = $data['electric_fee'] ?: 0;
        $data['public_relations_fee'] = $data['public_relations_fee'] ?: 0;
        $data['remarks'] = $data['remarks'] ?: '';
        $data['updated_at'] = date('Y-m-d H:i:s');
        try{
            if(!$data['year'] || !$data['month']) throw new \Exception('请选择年月');
            $data['ym'] = $data['year'] . '-' . $data['month'];
            unset($data['year'], $data['month']);
            if($id){ //编辑
                $res = XcRenterFee::where('id', $id)->first();
                if(!$res) throw new \Exception('无效的数据');
            } else { //从合同列表页面新增
                $contract = XcRenterContract::where('id', $contract_id)->first();
                if(!$contract) throw new \Exception('场租合同数据错误');
                $res = XcRenterFee::where(['renter_id' => $contract->renter_id, 'ym' => $data['ym']])->first();  //如果场租/物业已经插入了数据
            }
            if($res){
                XcRenterFee::where("id", $res->id)->update($data);
            } else {
                $data['renter_id'] = $contract->renter_id;
                $data['contract_id'] = $contract->id;
                $data['created_at'] = date('Y-m-d H:i:s');
                XcRenterFee::insert($data);
            }

            $data = [
                'code' => 0,
                'msg'  => 'success'
            ];
            return Response::json($data);
        }catch (\Exception $exception){
            $data = [
                'code' => -1,
                'msg'  => $exception->getMessage()
            ];
            return Response::json($data);
        }
    }

    public function weList(Request $request)
    {
        $renter_id = $request->get("renter_id");
        return View::make('admin.renter.weList', compact("renter_id"));
    }
    /**
     * 分页数据
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function weData(Request $request)
    {
        $renter_id = $request->get("renter_id");
        $res = XcRenterFee::query()->where('renter_id', $renter_id)->orderBy('id','desc')->paginate($request->get('limit',10))->toArray();

        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $res['total'],
            'data'  => $res['data'],
        ];
        return Response::json($data);
    }

    /**
     * -----------------------------------------------------合同-------------------------------------------------------
     *
     */
    public function contract(Request $request)
    {
        $renter_id = $request->get("renter_id");
        return View::make('admin.renter.contract', compact("renter_id"));
    }

    /**
     * 分页数据
     *
     */
    public function contractData(Request $request)
    {
        $renter_id = $request->get("renter_id");
        $res = XcRenterContract::query()->where('renter_id', $renter_id)->orderBy('id','desc')->paginate($request->get('limit',10))->toArray();

        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $res['total'],
            'data'  => $res['data'],
        ];
        return Response::json($data);
    }
}